import json

from selenium import webdriver
import time
import random
from label_pkt import label_this_pos

app_name = "Toutiao"

def run():
    with open("./config.json", "r", encoding="utf-8") as fd:
        config = json.load(fd)

    webdriver_path = config[app_name]["webdriver_path"]
    opt = webdriver.ChromeOptions()
    if "jd.com" in config[app_name]["index_url"]:
        print("禁用HTTP2")
        opt.add_argument("--disable-http2")
    
    browser_handle = None

    urls = list()
    with open(config[app_name]["url_file_path"], "r") as fd:
        urls = fd.readlines()
    cnt = 0
    for url in urls:
        # 每10轮清空一次缓存
        if cnt % 10 == 0:
            if browser_handle is not None:
                browser_handle.quit()
            browser_handle = webdriver.Chrome(chrome_options=opt, executable_path=webdriver_path)
            browser_handle.implicitly_wait(10)
            browser_handle.get(config[app_name]["index_url"])
            time.sleep(5)
        cnt += 1
        print("Current Processing URL index: " + str(cnt))
        new_tab = "window.open(\"{}\")".format(url.strip())
        print(new_tab)
        label_this_pos(url.strip() + " start")
        browser_handle.execute_script(new_tab)
        # 模拟浏览的时间
        sleep_random_interval(8, 30)
        browser_handle.switch_to.window(browser_handle.window_handles[1])
        browser_handle.close()
        label_this_pos(url.strip() + " end")
        # 切换回主页
        browser_handle.switch_to.window(browser_handle.window_handles[0])
        # 主页停留时间
        sleep_random_interval(2, 10)
    if browser_handle is not None:
        browser_handle.quit()


def sleep_random_interval(start, end):
    time.sleep(random.randint(start, end))
